package xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import xml.utils.XMLUtil;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class Test02 {
    static XMLUtil util = new XMLUtil();
    public static void main(String[] args) {
        String src = "src/xml/PhoneInfo.xml";
        try {
//            insert(src);
            delete(src);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新节点
    private static void update(String src) throws Exception{
        Document document = util.getDocument(src);
        NodeList brand = document.getElementsByTagName("Brand");
        for (int i = 0;i < brand.getLength();i++){
            Element item = (Element) brand.item(i);
            NodeList type = item.getElementsByTagName("Type");
            for (int j = 0;j < type.getLength();j++){
                Element item1 = (Element) type.item(j);
                if (item1.getAttribute("name").equals("note9")){
                    item1.setAttribute("name","note11");
                }
            }
        }
        util.saveXMLFile(document,src);
    }

    //添加节点
    private static void insert(String src) throws Exception{
        Document document = util.getDocument(src);
        Element brandElement = document.createElement("Brand");
        brandElement.setAttribute("name","小米");
        Element typeElement = document.createElement("Type");
        typeElement.setAttribute("name","note9");
        Element element = (Element) document.getElementsByTagName("PhoneInfo").item(0);

        brandElement.appendChild(typeElement);
        element.appendChild(brandElement);

        util.saveXMLFile(document,src);
    }

    //删除节点
    private static void delete(String src) throws Exception{
        Document document = util.getDocument(src);
        NodeList brand = document.getElementsByTagName("Brand");
        for (int i = 0;i < brand.getLength();i++){
            Element item = (Element) brand.item(i);
            if (item.getAttribute("name").equals("小米")){
                item.getParentNode().removeChild(item);
            }
        }
        util.saveXMLFile(document,src);
    }
}
